<?php


namespace App\Admin\Controllers;

use Illuminate\Http\Request;
use SmallRuralDog\Admin\Components\Form\Radio;
use SmallRuralDog\Admin\Components\Form\RadioGroup;
use SmallRuralDog\Admin\Components\Form\DatePicker;
use SmallRuralDog\Admin\Components\Grid\Image;
use SmallRuralDog\Admin\Components\Grid\Tag;
use SmallRuralDog\Admin\Controllers\AdminController;
use SmallRuralDog\Admin\Grid;
use SmallRuralDog\Admin\Grid\Actions\ActionButton;
use SmallRuralDog\Admin\Layout\Content;
use SmallRuralDog\Admin\Components\Widgets\Dialog;
use SmallRuralDog\Admin\Components\Widgets\BaseForm;
use SmallRuralDog\Admin\Components\Attrs\SelectOption;
use SmallRuralDog\Admin\Components\Form\Select;
use App\Models\Order;
use App\Models\Member;
// use App\Models\MemberScoreLog;
use App\Models\OrderLog;
use App\Models\ExpressCompany;
use App\Models\DeliveryDetail;
use App\Models\Delivery;

class OrderController extends AdminController
{

    public function grid()
    {
        $grid = new Grid(new Order());

        $grid->defaultSort('order_id', 'desc');

        $grid->model();

        $grid->quickSearch(['order_bn']);

        $grid->column('order_bn', "订单编号")->width(150)->sortable();

        $grid->column('member.nickname', '会员')->width(120);

        $grid->column('image.path', "商品图片")->width(70)->customValue(function ($row, $value) {
            // dd($value);
            return $value ?? ''; // 只显示第一张图片
        })->component(Image::make()->size(50, 50)->preview())->align("center");

        // $grid->column('detail.goods_name', " ")->width(200);
        $grid->column('detail.goods_name', " ")->width(200)->customValue(function ($row, $value) {
            $v = [];
            foreach($value as $val)
            {
                $v[] = $val;
            }
            $v = implode("<br/><br/><br/><br/>", $v);
            return $v; // 只显示第一张图片
        })->align("center");
        // $grid->column('detail.goods_price', "商品价值")->itemSuffix('元')->width(120);
        $grid->column('goods_price', "商品价值")->itemSuffix('元')->width(100);

        $grid->column('status', "订单状态")->width(100)->align("center")->customValue(function ($row, $value) {
            $status = ['active'=>'正常','invalid'=>'作废','done'=>'完成'];
            return $status[$value];
        })->component(Tag::make()->type(["正常" => "success", "作废" => "danger", "完成" => "info"]));

        $grid->column('pay_status', "支付状态")->width(100)->align("center")->customValue(function ($row, $value) {
            $pay_status = ['notpay'=>'待支付','paid'=>'支付成功','refunded'=>'已退款'];
            return $pay_status[$value];
        })->component(Tag::make()->type(["待支付" => "warning", "支付成功" => "success", "已退款" => "danger"]));

        $grid->column('ship_status', "发货状态")->width(100)->align("center")->customValue(function ($row, $value) {
            $ship_status = ['notdelivery'=>'未发货','shipped'=>'已发货','returned'=>'已退款'];
            return $ship_status[$value];
        })->component(Tag::make()->type(["未发货" => "warning", "已发货" => "success", "已退款" => "danger"]));

        $grid->column('amount', '订单总额')->itemSuffix('元')->width(80);
        $grid->column('payment_code_name', '支付方式')->width(100);
        $grid->column('paid_amount', '支付金额')->itemSuffix('元')->width(80);
        $grid->column('payed_time', '支付时间')->width(150)->sortable();

        $grid->column('member_address', '收货地址')->width(150);
        $grid->column('address.consignee', '收货人')->width(80);
        $grid->column('address.mobile', '联系电话')->width(80);
        $grid->column('delivery.ship_company', '物流公司')->width(80)->customValue(function ($row, $value) {
            $express_name = [];
            foreach ($value as $val)
            {
                if (!$val) continue;
                $express = ExpressCompany::where('id', $val)->first();
                $express_name[] = $express->name ;
            }
            return implode(',', $express_name) ?? '-';
        });
        $grid->column('delivery.ship_number', '物流单号')->width(120)->customValue(function ($row, $value) {
            $express_number = [];
            foreach ($value as $val)
            {
                if (!$val) continue;
                $express_number[] = $val;
            }
            return implode(',', $express_number) ?? '-';
        });

        $grid->column('created_at', '下单时间')->width(150)->sortable();

        $grid->column('remark', '买家留言')->showOverflowTooltip();


        $grid->actions(function (Grid\Actions $actions){

            $actions->hideDeleteAction(); // 隐藏删除操作
            $actions->hideEditAction(); // 隐藏编辑操作

            if ( $actions->getRow()->status=='active' && $actions->getRow()->pay_status=='paid' && $actions->getRow()->ship_status=='notdelivery')
            {
                // $actions->add(ActionButton::make("发货")->order(3)->handler('request')->uri(route("admin.order.delivery").'/?id='.$actions->getRow()->order_id)->message('发货之后订单将处于完成状态，确定要发货该笔订单吗？'));
                $actions->add(ActionButton::make("发货")->order(4)->dialog(function (Dialog $dialog) use ($actions) {
                    $dialog->title("订单发货")->showClose(true)->width('600px');
                    $dialog->slot(function (Content $content) use ($actions) {
                        $baseForm = new BaseForm();
                        $baseForm->action(route("admin.order.delivery"));
                        $baseForm->emit("closeDialog");
                        $baseForm->emit("tableReload");
                        $baseForm->addValue("order_id", $actions->getRow()->order_id);
                        $baseForm->item('ship_company', '物流公司')->component(Select::make(0)->options(function () {
                            return ExpressCompany::query()->orderBy('id')->get()->map(function ($item) {
                                return SelectOption::make($item->id, $item->name);
                            })->prepend(SelectOption::make(0, '全部'));
                        }));
                        $baseForm->item("ship_number", "物流单号");
                        // $baseForm->hideTab(true);
                        $content->row($baseForm);
                    });
                }));
            }

            if ( $actions->getRow()->status=='active')
            {
                $actions->add(ActionButton::make("作废")->order(4)->dialog(function (Dialog $dialog) use ($actions) {
                    $dialog->title("作废订单")->showClose(true)->width('600px');
                    $dialog->slot(function (Content $content) use ($actions) {
                        $baseForm = new BaseForm();
                        $baseForm->action(route("admin.order.invalid"));
                        $baseForm->emit("closeDialog");
                        $baseForm->emit("tableReload");
                        $baseForm->addValue("order_id", $actions->getRow()->order_id);
                        $baseForm->item("return", "是否退款")->component(RadioGroup::make(1)->options([
                            Radio::make(1, "退款"),
                            Radio::make(2, "不退款"),
                        ]));
                        $baseForm->item("remark", "说明");
                        // $baseForm->hideTab(true);
                        $content->row($baseForm);
                    });
                }));
            }

        })->toolbars(function (Grid\Toolbars $toolbars)
        {
            $toolbars->hideCreateButton();
        });

        $grid->filter(function (Grid\Filter $filter) {

            $filter->date('created_at', '下单日期')->component(DatePicker::make());

            $filter->equal('ship_status', '发货状态')->component(RadioGroup::make(null, [
                Radio::make('notdelivery', '未发货'),
                Radio::make('shipped', '已发货'),
                Radio::make('returned', '已退货'),
            ]));

        });
        $grid->quickSearchPlaceholder("请输入订单号");

        return $grid;
    }


    // 订单作废
    public function invalidOrder(Request $request)
    {
        try {
            \Admin::validatorData($request->all(), [
                'order_id' => 'required',
                'return' => 'required'
            ]);
            $order_id = $request->input("order_id");
            $return = $request->input("return");
            $remark = $request->input("remark");

            $order = Order::where('order_id', $order_id)->first();
            if (!$order)
            {
                return \Admin::responseError('获取订单信息失败');
            }

            if (!$order->status == 'invalid')
            {
                return \Admin::responseError('订单已经是作废状态，请勿重复操作');
            }

            if (!$order->status == 'done')
            {
                return \Admin::responseError('订单已经是完成，无法操作');
            }

            // 修改订单状态
            $order->status = 'invalid';
            $order->save();

            // 执行退款 @todo
            if ($return == '1')
            {
                // 更新会员表
                // $member = Member::query()->findOrFail($order->member_id);

                // @todo 执行退款

                // 记录订单操作日志
                $res = OrderLog::create([
                    'order_id' => $order->order_id,
                    'order_bn' => $order->order_bn,
                    'member_id' => $order->member_id,
                    'source' => 'admin',
                    'op_id' => \Admin::user()->id,
                    'op_name' => \Admin::user()->username,
                    'behavior' => OrderLog::ORDER_INVALID,
                    'status' => 'success',
                    'content' => '管理员手动作废订单: ' . $remark,
                ]);
                // dd($res);
            }

        } catch (\Exception $exception) {
            return \Admin::responseError($exception->getMessage());
        }

        return \Admin::responseMessage('订单作废成功');
    }

    // 订单发货
    public function deliveryOrder(Request $request)
    {
         try {
            \Admin::validatorData($request->all(), [
                'order_id' => 'required',
                'ship_company' => 'required',
                'ship_number' => 'required',
            ],[
                'order_id.required' => '参数错误',
                'ship_company.required' => '参数错误',
                'ship_number.required' => '参数错误',
            ]);
            $order_id = $request->input("order_id");
            $ship_company = $request->input("ship_company");
            $ship_number = $request->input("ship_number");


            $order = Order::where('order_id', $order_id)->with('detail')->first();
            // dd('ss',$order->toArray());
            if (!$order)
            {
                return \Admin::responseError('获取订单信息失败');
            }

            if (!$order->status == 'invalid')
            {
                return \Admin::responseError('订单已经是作废状态，无法发货');
            }

            if (!$order->status == 'done')
            {
                return \Admin::responseError('订单已经是完成，无法操作');
            }

            if ($order->pay_status == 'notpay' || $order->pay_status == 'returned')
            {
                return \Admin::responseError('订单已经是未支付或退款状态，无法发货');
            }

            if (!$order->ship_status == 'shipped')
            {
                return \Admin::responseError('订单已经发货完成，请勿重复操作');
            }

            // 去发货
            $order->status = 'done';
            $order->ship_status = 'shipped';
            $res = $order->save();

            if (!$res)
            {
                return \Admin::responseError('订单发货失败');
            }

            $expressCompany = ExpressCompany::where('id', $ship_company)->first();

            // 生成发货记录
            $deliveryData = [
                'order_bn' => $order->order_bn,
                'member_id' => $order->member_id,
                'type' => 'delivery',
                'status' => 'success',
                'ship_company' => $ship_company,
                'ship_number' => $ship_number,
                'remark' => '物流公司：'.$expressCompany->name.", 物流单号：".$ship_number,
            ];
            $delivery = Delivery::query()->create($deliveryData);

            if ($delivery)
            {
                $deliveryDetailData = [];
                foreach ($order->detail as $dkey=>$dval)
                {
                    $deliveryDetailData = [
                        'delivery_id' => $delivery->delivery_id,
                        'goods_id' => $dval['goods_id'],
                        'sku_id' => $dval['sku_id'],
                        'goods_name' => $dval['goods_name'],
                        'num' => $dval['num'],
                    ];
                    DeliveryDetail::query()->create($deliveryDetailData);
                }
            }

            // 记录订单核销日志
            OrderLog::query()->create([
                'order_id' => $order->order_id,
                'order_bn' => $order->order_bn,
                'source' => 'admin',
                'op_id' => \Admin::user()->id,
                'op_name' => \Admin::user()->username,
                'behavior' => OrderLog::ORDER_DELIVERY,
                'member_id' => $order->member_id,
                'status' => 'success',
                'content' => '管理员手动发货,'.$deliveryData['remark'],
            ]);

        } catch (\Exception $exception) {
            return \Admin::responseError($exception->getMessage());
        }

        return \Admin::responseMessage('订单发货成功');
    }

}
